export function list2tree(data, id = "id", parentId = "parentId", // eslint-disable-next-line no-unused-vars
                          children = "children", rootId = 0, proChildren = "children") {
  // 對源數據深度克隆
  const cloneData = JSON.parse(JSON.stringify(data));
  // 循環所有項
  const treeData = cloneData.filter((father) => {
    const branchArr = cloneData.filter((child) => {
      // 返回每一項的子級數組
      return father[id] === child[parentId];
    });

    branchArr.length > 0 ? (father[proChildren] = branchArr) : "";
    // 返回第一層
    return father[parentId] === rootId;
  });
  return treeData !== "" ? treeData : data;
}

export function debounce(fn, delay = 500) {
  let timer = null;
  return function() {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, arguments);
    }, delay);
  };
}

export function deepClone(obj) {
  let clone = Array.isArray(obj) ? [] : {};
  for (const key in obj) {
    let item = obj[key];
    if (item) {
      //实现方法的克隆
      if (item instanceof Function) {
        clone[key] = new Function("return " + item.toString())();
      } else if (item instanceof Object) {
        clone[key] = deepClone(item);
      } else {
        clone[key] = item;
      }
    }
  }
  return clone;
}

export function scrollToTarget(targetId) {
  const targetDom = document.getElementById(targetId);
  scrollToPageTop(targetDom.offsetTop);
}

export function scrollToPageTop(offsetTop) {
  const mainDom = document.querySelectorAll("#container")[0];
  mainDom.scrollTo({ top: offsetTop - 100 });
}
